package com.action.boot.jpa.service;

import com.action.boot.jpa.config.web.BusinessException;
import com.action.boot.jpa.repository.UserInfo;
import com.action.boot.jpa.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Wuxiang on 2017/3/25.
 */
@Service
public class UserService {
    @Autowired
    UserInfoRepository userInfoRepository;

    public Iterable<UserInfo> findAll() {
        return userInfoRepository.findAll();
    }

    public List<UserInfo> findByName(String name) {
        List<UserInfo> userInfos = userInfoRepository.findByName(name);
        if (userInfos.size() == 0) {
            throw new BusinessException("没有该姓名的用户！");
        }
        return userInfos;
    }

    public List<UserInfo> findAgeNull() {
        return userInfoRepository.findAgeNull();
    }

    public List<UserInfo> findByAge(String age) throws Exception {
        List<UserInfo> userInfos = userInfoRepository.findByAge(age);
        if (userInfos.size()==0) {
            throw new Exception("没有该年龄的用户！");
        }
        return userInfos;
    }

    public UserInfo findById(Long id) {
        UserInfo userInfo = userInfoRepository.findOne(id);
        if (userInfo == null) {
            throw new BusinessException("未根据id找到该用户！");
        }
        return userInfo;
    }

    public void deleteById(Long id) {
        findById(id);
        userInfoRepository.delete(id);
    }

    public void update(UserInfo userInfo) {
        if (userInfo.getId() == null) {
            throw new BusinessException("id不能为空！");
        }
        if (userInfo.getAge() == null) {
            throw new BusinessException("age不能为空！");
        }
        if (userInfo.getName() == null) {
            throw new BusinessException("name不能为空！");
        }
        if (userInfo.getPassword() == null) {
            throw new BusinessException("password不能为空！");
        }
        findById(userInfo.getId());
        userInfoRepository.save(userInfo);
    }

    public UserInfo insert(UserInfo userInfo) {
        if (userInfo.getAge() == null) {
            throw new BusinessException("age不能为空！");
        }
        if (userInfo.getName() == null) {
            throw new BusinessException("name不能为空！");
        }
        if (userInfo.getPassword() == null) {
            throw new BusinessException("password不能为空！");
        }
        return userInfoRepository.save(userInfo);
    }
}
